package com.topscomm.file.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 文件操作
 *
 * @description:
 * @author: donghang
 * @date: 2020年8月19日下午6:10:16
 * @modify:
 */
public class FileUtil {
	/**
	 * 文件加密
	 *
	 * @description:
	 * @param filePath
	 * @param key
	 * @throws Exception
	 * @author: donghang
	 * @date: 2020年8月19日下午5:42:23
	 * @modify:
	 */
	public static void encrypt(String filePath, String key) throws Exception {
		File file = new File(filePath);
		if (!file.exists()) {
			throw new FileNotFoundException(filePath + "文件不存在");
		}
		String destFilePath = file.getParent() + "/" + "encrypt-" + file.getName();
		File destfile = new File(destFilePath);
		if (destfile.exists()) {
			destfile.delete();
		}
		try(    // 获取待加密文件的输入流
				InputStream in = new FileInputStream(filePath);
				// 创建中转文件输出流
				OutputStream out = new FileOutputStream(destFilePath)
				){
			// 待加密文件的流
			byte[] oldBuffer = new byte[1024];
			// 加密之后的文件的流
			byte[] encryptBuffer = new byte[1024];
			int readByteCount;
			while ((readByteCount = in.read(oldBuffer)) > 0) {
				for (int i = 0; i < readByteCount; i++) {
					byte b = oldBuffer[i];
					// 每个字节加2加密
					b += 2;
					encryptBuffer[i] = b;

				}
				out.write(encryptBuffer, 0, readByteCount);
				out.flush();
			}
		}

	}

	/**
	 * 解密文件
	 *
	 * @description:
	 * @param filePath
	 * @param tempFilePath
	 * @param keyLength
	 * @return
	 * @throws Exception
	 * @author: donghang
	 * @date: 2020年8月19日下午5:54:48
	 * @modify:
	 */
	public static String decrypt(String filePath, String tempFilePath, int keyLength) throws Exception {
		File file = new File(filePath);
		if (!file.exists()) {
			throw new FileNotFoundException(filePath + "文件不存在");
		}
		// 创建文件夹
		File dest = new File(tempFilePath);
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}
		// 获取待解密的文件输入流
		InputStream is = new FileInputStream(filePath);
		// 创建目标文件输出流，用来生成解密后的文件
		OutputStream out = new FileOutputStream(tempFilePath);
		byte[] buffer = new byte[1024];
		byte[] decryptBuffer = new byte[1024];
		// 去除尾部加密串
		long size = file.length() - keyLength;
		int mod = (int) (size % 1024);
		int div = (int) (size >> 10);
		int blockCount = mod == 0 ? div : (div + 1);
		int blockNum = 1, readByteCount;
		while ((blockNum <= blockCount && (readByteCount = is.read(buffer)) > 0)) {
			if (mod != 0 && blockNum == blockCount) {
				readByteCount = mod;
			}
			for (int i = 0; i < readByteCount; i++) {
				byte b = buffer[i];
				b -= 2;
				decryptBuffer[i] = b;
			}
			out.write(decryptBuffer, 0, readByteCount);
			blockNum++;
		}
		out.close();
		is.close();
		return tempFilePath;
	}

}
